package main

import (
	"fmt"
	"micro-rulego/internal/conf"
	zlog "micro-rulego/pkg/zap"

	"github.com/go-kratos/kratos/v2/log"
	"go.uber.org/zap"
)

type ZapLogger struct {
	log  *zap.Logger
	Sync func() error
}

func newLogger(l *conf.Logger) log.Logger {
	zapConfig := &zlog.Config{
		Level:         l.Level,
		Format:        l.Format,
		Director:      l.Director,
		ShowLine:      l.ShowLine,
		EncodeLevel:   l.EncodeLevel,
		StacktraceKey: l.StacktraceKey,
		LogInConsole:  l.LogInConsole,
		LogInFile:     l.LogInFile,
		MaxAge:        l.MaxAge,
	}

	logger := zlog.NewZapLogger(
		zapConfig,
	)
	if l.LogWithName {
		logger = logger.With(zap.String("name", Name))
	}
	return &ZapLogger{log: logger, Sync: logger.Sync}
}

// Log Implementation of logger interface.
func (l *ZapLogger) Log(level log.Level, keyvals ...interface{}) error {
	if len(keyvals) == 0 || len(keyvals)%2 != 0 {
		l.log.Warn(fmt.Sprint("Keyvalues must appear in pairs: ", keyvals))
		return nil
	}
	// Zap.Field is used when keyvals pairs appear
	var data []zap.Field
	for i := 0; i < len(keyvals); i += 2 {
		data = append(data, zap.Any(fmt.Sprint(keyvals[i]), fmt.Sprint(keyvals[i+1])))
	}
	switch level {
	case log.LevelDebug:
		l.log.Debug("", data...)
	case log.LevelInfo:
		l.log.Info("", data...)
	case log.LevelWarn:
		l.log.Warn("", data...)
	case log.LevelError:
		l.log.Error("", data...)
	}
	return nil
}
